import { shareAppMessageSet } from "../../../utils/config"
import { dataCollection } from "../../../utils/dataCollection"
import { Traffic } from "./polyline/traffic"
const traffic = new Traffic()
let key = ''


//地图缩放比例尺 【3 - 20】最小3，最大20
const scaleRatio = [100000, 500000, 200000, 100000, 50000, 25000, 20000, 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5]

Page({

  /**
   * 页面的初始数据
   */
  data: {
    startingPoint: {
      longitude: 0,//经度
      latitude: 0,//纬度
      address: '',
    },
    target: {
      longitude: 0,//经度
      latitude: 0,//纬度
      name: '',
      address: '',
    },
    mapCenterPoint: {
      longitude: 114.025469,//中心经度
      latitude: 22.567979,//中心纬度
    },
    polyline: <any[]>[],
    markers: <any[]>[],
    allLine: <any[]>[],
    busLineList: 0,
    selectVehicleIndex: 0,
    vehicle: [
      // { defaultIcon: '../../../images/changdisan_icon_ditie_wxz@2x.png', activeIcon: '../../../images/changdisan_icon_ditie_xz@2x.png', name: '打车' },
      { defaultIcon: '../../../images/changdisan_icon_ditie_wxz@2x.png', activeIcon: '../../../images/changdisan_icon_ditie_xz@2x.png', name: '地铁' },
      { defaultIcon: '../../../images/changdisan_icon_gongjiao_wxz@2x.png', activeIcon: '../../../images/changdisan_icon_gongjiao_xz@2x.png', name: '公交' },
    ],
    path: <any[]>[],
    //所有交通的交通路线
    vehicleData: {
      index: 0,//默认选择当前交通方式的第一条线路
      // driving: {
      //   path: [],
      //   polyline: []
      // },
      bus: {
        path: [],
        polyline: []
      },
      subway: {
        path: <any>[],
        polyline: []
      }
    },
    userFuzzyLocation: false,//默认用户没有授权获取地理位置
    customCalloutMarkerIds: [1],
    windowHeight: 0,
    boxHeight: 0,
    transition: 'none',
    isPC: false,
    mapScale: 13,
    show: false,
    themeCode:''
  },
  unflod: false, //默认是没有展开
  onLoad(options: any) {
    //从本地获取当前选择的城市编码
    this.setData({
      themeCode: wx.getStorageSync('themeCode')
    })

    key = options.name

    const coords = wx.getStorageSync('coords')
    console.log('coords', coords)
    const userLocation = wx.getStorageSync('userLocation')
    this.setData({
      'startingPoint.latitude': coords.latitude,
      'startingPoint.longitude': coords.longitude,
      'startingPoint.address': userLocation,
      'target.latitude': options.lat,
      'target.longitude': options.lng,
      'target.name': options.name,
      'target.address': options.address,
      isPC:wx.getStorageSync('isPC')||false
    })

    wx.getSystemInfo({
      success: (res: any) => {
        console.log(res)
        this.setData({
          windowHeight: res.windowHeight,
          boxHeight: res.windowHeight * 0.4
        })

        wx.getSetting({
          success: (e: any) => {
            console.log('getSetting', e)
            if (e.authSetting['scope.userLocation']) {
              this.userAuthorization()
            } else {
              console.log('用户没有授权', this.data.target.name)
              this.userNotAuthorization()
            }
          }
        })
      }
    })
  },
  //用户已经授权获取地理位置
  userAuthorization() {
    this.setData({
      userFuzzyLocation: true
    })
    wx.authorize({
      scope: 'scope.userLocation',
      success: (res: any) => {
        // 用户已经同意小程序使用获取地理位置
        console.log('用户已经同意小程序使用获取地理位置', res)
        this.getTrafficDetail()
      }
    })
  },
  //用户没有授权获取地理位置
  userNotAuthorization() {
    //用户没有授权获取地理位置信息，择默认展示科目三场地位置
    this.setData({
      markers: [
        {
          id: 1,
          latitude: this.data.target.latitude,
          longitude: this.data.target.longitude,
          iconPath: '../../../images/kscdxq_icon_qds@2x.png',
          callout: {
            content: this.data.target.name,
            color: '#000',
            fontSize: 14,
            borderRadius: 10,
            bgColor: '#fff',
            padding: 6,
            display: 'ALWAYS',
            textAlign: 'center'
          },
          width: 26,
          height: 30
        }
      ],
      'mapCenterPoint.latitude': this.data.target.latitude,
      'mapCenterPoint.longitude': this.data.target.longitude,
    })
  },
  //电脑端默认是授权了地理位置
  userAuthorizationByPC() {
    this.setData({
      userFuzzyLocation: true
    })
    this.getTrafficDetail()
  },
  //监听选择的交通
  onSelectVehicle(res: any) {
    const index = Number(res.currentTarget.dataset.index)
    this.setData({
      selectVehicleIndex: index,
      'vehicleData.index': 0,
      transition: 'none',
    })
    this.recoverHeight()

    if (index === 0) {
      this.getTrafficDetail()
    }
  },
  getTrafficDetail() {
    traffic.onSubway(this.data.startingPoint, this.data.target, (res: any) => {
      console.log('路线', res)
      if (res.polyline.length) {
        this.setPolylineData(res, 'subway')
      } else {
        //没有数据的情况下，默认显示终点
        console.log('没有数据的情况下，默认显示终点')
        this.userNotAuthorization()
      }
    })
  },
  setPolylineData(res: any, type: string) {
    if (type === 'subway') {
      this.setData({
        'vehicleData.subway.polyline': [...res.polyline],
        'vehicleData.subway.path': [...res.path]
      })
    }
    this.setMapPath()
    this.setPath()
  },
  //选择线路
  onSelectPath(res: any) {
    const index = res.currentTarget.dataset.index
    console.log([this.data.selectVehicleIndex, index])
    if (index !== this.data.vehicleData.index) {
      this.setData({
        'vehicleData.index': index
      })
      this.setMapPath()
    }
  },
  setMapPath() {
    const centerPoint = {
      longitude: (Number(this.data.startingPoint.longitude) + Number(this.data.target.longitude)) / 2,//中心经度
      latitude: (Number(this.data.startingPoint.latitude) + Number(this.data.target.latitude)) / 2,//中心纬度
    }

    const path: any[] = []
    const polyline: any[] = []
    if (this.data.selectVehicleIndex === 0) {
      //地铁
      polyline.push(...JSON.parse(JSON.stringify(this.data.vehicleData.subway.polyline)))
    }
    path.forEach((item: any[]) => {
      const l: { name: string, type: string }[] = []
      item.forEach((child: any) => {
        if (l.length === 0) {
          l.push(...child.lines)
        } else {
          l.forEach((b: { name: string, type: string }, j: number) => {
            if (child.lines[j] !== b) {
              l[j].name = b.name + '/' + child.lines[j].name
            }
          })
        }
      })
      item[0].lines = [...l]
    })

    this.setData({
      markers: [
        {
          id: 1,
          latitude: this.data.startingPoint.latitude,
          longitude: this.data.startingPoint.longitude,
          iconPath: '../../../images/kscdxq_icon_qd@2x.png',
          width: 26,
          height: 30
        },
        {
          id: 2,
          latitude: this.data.target.latitude,
          longitude: this.data.target.longitude,
          iconPath: '../../../images/kscdxq_icon_zd@2x.png',
          width: 26,
          height: 30
        }
      ],
      mapCenterPoint: centerPoint,
      polyline: polyline.length ? (polyline[this.data.vehicleData.index].length ? [...polyline[this.data.vehicleData.index].flat()] : []) : [],
    })
    if (this.data.vehicleData.subway.path.length) {
      const distance = this.data.vehicleData.subway.path[this.data.vehicleData.index][0].distance

      const s = scaleRatio.findIndex((n, m) => {
        console.log(n, m)
        return n <= distance / 5
      })

      console.log('mapScale', distance, s + 3)

      this.setData({
        mapScale: s + 3
      })
    }


    this.recoverHeight()
  },
  setPath() {
    const path: any[] = []
    if (this.data.selectVehicleIndex === 0) {
      //地铁
      path.push(...JSON.parse(JSON.stringify(this.data.vehicleData.subway.path)))
    }
    this.setData({
      path: [...path]
    })
  },
  //打开导航
  onOpenMap() {
    const customOpenMapComponent = this.selectComponent('.customOpenMap')
    customOpenMapComponent.openMap({
      latitude: Number(this.data.target.latitude),
      longitude: Number(this.data.target.longitude),
      destination: this.data.target.name,
    })
  },
  //点击地图上的气泡
  onCalloutTap(e: any) {
    // console.log('e')
  },
  transform: {
    startpageY: 0,
    startmoveY: 0,
  },
  onTouchstart(e: any) {
    this.transform.startpageY = e.changedTouches[0].pageY
    this.transform.startmoveY = 0
    // console.log('start', e, this.transform.startpageY)
  },
  onTouchmove(e: any) {
    this.transform.startmoveY = this.transform.startpageY - e.changedTouches[0].pageY
  },
  onTouchend(e: any) {
    // console.log('end', e, this.transform.startmoveY)
    if (this.transform.startmoveY > 10) {
      this.unflod = true
      this.setData({
        boxHeight: this.data.windowHeight * 0.9,
        transition: 'all 0.5s'
      })
    } else if (this.transform.startmoveY < -10) {
      this.unflod = false
      this.setData({
        boxHeight: this.data.windowHeight * 0.4,
        transition: 'all 0.5s'
      })
    }
  },
  //恢复信息框的高度
  recoverHeight() {
    if (this.unflod) {
      this.unflod = false
      this.setData({
        transition: 'all 0.35s',
        boxHeight: this.data.windowHeight * 0.4
      })
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return { ...shareAppMessageSet() }
  },
  onHide() {
    dataCollection.setPageMapData('leave')
    dataCollection.setComprehensiveMapData(key, 'leave', 'site')
  },
  onShow() {
    dataCollection.setPageMapData('enter', '科三页面')
    dataCollection.setComprehensiveMapData(key, 'enter', 'site')
  },
  onUnload() {
    dataCollection.setPageMapData('leave')
    dataCollection.setComprehensiveMapData(key, 'leave', 'site')
  }
})